<template>
	<div class="container">
		<!-- 概览统计卡片 -->
		<a-row gutter="16">
			<a-col :span="4">
				<a-card title="总租客数">{{ overview.totalUsers }}</a-card>
			</a-col>
			<a-col :span="4">
				<a-card title="总房东数">{{ overview.totalLandlords }}</a-card>
			</a-col>
			<a-col :span="4">
				<a-card title="房源总量">{{ overview.totalHouses }}</a-card>
			</a-col>
			<a-col :span="4">
				<a-card title="预约记录数">{{ overview.totalAppointments }}</a-card>
			</a-col>
			<a-col :span="4">
				<a-card title="在线聊天记录数">{{ overview.totalMessages }}</a-card>
			</a-col>
		</a-row>

		<!-- 房源地理分布卡片 -->
		<a-card title="房源地理分布" style="margin-top: 24px">
			<a-radio-group v-model:value="geoType" @change="fetchGeoDistribution">
				<a-radio-button value="business">商圈</a-radio-button>
				<a-radio-button value="subway">地铁站</a-radio-button>
			</a-radio-group>
			<div ref="geoChartContainer" style="height: 400px; margin-top: 16px"></div>
		</a-card>

<!--		&lt;!&ndash; 趋势统计图卡片 &ndash;&gt;-->
<!--		<a-card title="趋势统计" style="margin-top: 24px">-->
<!--			<a-space style="margin-bottom: 16px">-->
<!--				<a-radio-group v-model:value="trendType">-->
<!--					<a-radio-button value="house">房源</a-radio-button>-->
<!--					<a-radio-button value="appointment">预约</a-radio-button>-->
<!--					<a-radio-button value="message">消息</a-radio-button>-->
<!--				</a-radio-group>-->
<!--				<a-date-picker v-model:value="trendStartDate" placeholder="开始日期" style="width: 120px" />-->
<!--				<a-date-picker v-model:value="trendEndDate" placeholder="结束日期" style="width: 120px" />-->
<!--				<a-select v-model:value="trendGranularity" style="width: 100px">-->
<!--					<a-select-option value="day">天</a-select-option>-->
<!--					<a-select-option value="month">月</a-select-option>-->
<!--					<a-select-option value="year">年</a-select-option>-->
<!--				</a-select>-->
<!--				<a-button type="primary" @click="onFetchTrend">查询</a-button>-->
<!--			</a-space>-->
<!--			<div ref="trendChartContainer" style="height: 400px"></div>-->
<!--		</a-card>-->

		<!-- 用户行为统计卡片 -->
		<a-card title="用户行为统计" style="margin-top: 24px">
			<!-- 指标切换 -->
			<a-space style="margin-bottom: 16px">
				<a-radio-group v-model:value="behaviorType" @change="fetchUserBehavior">
					<a-radio-button value="browse">浏览量</a-radio-button>
					<a-radio-button value="favorite">收藏量</a-radio-button>
					<a-radio-button value="appointment">预约量</a-radio-button>
<!--					<a-radio-button value="conversion">转化率（预约数/浏览数）</a-radio-button>-->
				</a-radio-group>
			</a-space>
			<!-- 用户行为图表 -->
			<div ref="userBehaviorChartContainer" style="height: 400px"></div>
		</a-card>

		<!-- 房东运营情况卡片 -->
		<a-card title="房东运营情况" style="margin-top: 24px">
			<a-table
				:columns="landlordColumns"
				:dataSource="landlordPerformance"
				rowKey="landlordId"
				style="margin-bottom: 16px"
			/>
		</a-card>
	</div>
</template>

<script setup>
	import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
	import adminApi from '@/api/adminApi';
	import { message } from 'ant-design-vue';
	import * as echarts from 'echarts';
	import dayjs from 'dayjs';

	// ----------------------
	// 数据定义
	// ----------------------

	// 概览数据
	const overview = ref({
		totalUsers: 0,
		totalLandlords: 0,
		totalHouses: 0,
		totalAppointments: 0,
		totalMessages: 0
	});

	// 用户行为数据汇总（用于文字显示，如果接口有提供也可忽略）
	const userBehavior = ref({
		totalBrowsing: 0,
		totalFavorites: 0,
		totalAppointments: 0,
		conversionRate: 0
	});

	// 用于切换用户行为图表指标的类型
	const behaviorType = ref('browse');

	// 房东运营情况数据及表格列
	const landlordPerformance = ref([]);
	const landlordColumns = [
		{ title: '房东ID', dataIndex: 'landlordId' },
		{ title: '房东姓名', dataIndex: 'landlordName' },
		{ title: '房源总数', dataIndex: 'totalHouses' },
		{ title: '预约记录数', dataIndex: 'totalAppointments' }
	];

	// 趋势图相关数据及控制变量
	const trendData = ref([]);
	const trendType = ref('house');
	const trendStartDate = ref(dayjs().subtract(7, 'day')); // 保持 dayjs 对象
	const trendEndDate = ref(dayjs()); // 保持 dayjs 对象
	const trendGranularity = ref('day');

	// 地理分布相关
	const geoData = ref([]);
	const geoType = ref('business');

	// ----------------------
	// 图表容器引用及实例
	// ----------------------
	const trendChartContainer = ref(null);
	let trendChartInstance = null;

	const geoChartContainer = ref(null);
	let geoChartInstance = null;

	const userBehaviorChartContainer = ref(null);
	let userBehaviorChartInstance = null;

	// ----------------------
	// 图表更新函数
	// ----------------------

	// 更新趋势图（折线图）
	const updateTrendChart = () => {
		const periods = trendData.value.map((item) => item.period);
		const counts = trendData.value.map((item) => item.count);
		const option = {
			title: { text: '房源趋势统计', left: 'center' },
			tooltip: { trigger: 'axis' },
			toolbox: {
				feature: {
					dataZoom: {},
					restore: {},
					saveAsImage: {}
				}
			},
			xAxis: {
				type: 'category',
				boundaryGap: false,
				data: periods
			},
			yAxis: {
				type: 'value',
				min: 1,
				minInterval: 1,
				axisLabel: {
					formatter: (val) => parseInt(val, 10)
				}
			},
			series: [
				{
					name: '数量',
					type: 'line',
					smooth: true,
					data: counts,
					markPoint: {
						data: [
							{ type: 'max', name: '最大值' },
							{ type: 'min', name: '最小值' }
						]
					}
				}
			]
		};
		if (trendChartInstance) {
			trendChartInstance.setOption(option, true);
		}
	};

	// 更新用户行为图（折线图）
	// 接口返回的数据为每天的统计数据，用于生成曲线图
	const updateUserBehaviorChart = () => {
		const periods = userBehaviorTrend.value.map((item) => item.period);
		const counts = userBehaviorTrend.value.map((item) => item.count);
		const option = {
			// title: { text: behaviorType.value + '趋势统计', left: 'center' },
			tooltip: { trigger: 'axis' },
			xAxis: {
				type: 'category',
				data: periods
			},
			yAxis: {
				type: 'value',
				min: 1,
				minInterval: 1,
				axisLabel: {
					formatter: (val) => parseInt(val, 10)
				}
			},
			series: [
				{
					data: counts,
					type: 'line',
					smooth: true
				}
			]
		};
		if (userBehaviorChartInstance) {
			userBehaviorChartInstance.setOption(option, true);
		}
	};

	// 更新地理分布饼图
	const updateGeoChart = () => {
		const fieldName = geoType.value === 'business' ? 'area' : 'station';
		const option = {
			title: { text: geoType.value === 'business' ? '商圈分布' : '地铁站分布', left: 'center' },
			tooltip: { trigger: 'item' },
			legend: {
				orient: 'vertical',
				left: 'left',
				data: geoData.value.map((item) => item[fieldName])
			},
			series: [
				{
					name: '房源数量',
					type: 'pie',
					radius: '50%',
					data: geoData.value.map((item) => ({
						value: item.count,
						name: item[fieldName]
					})),
					emphasis: {
						itemStyle: {
							shadowBlur: 10,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		};
		if (geoChartInstance) {
			geoChartInstance.setOption(option);
		}
	};

	// ----------------------
	// 数据获取函数（接口调用）
	// ----------------------

	// 保存用户行为趋势数据
	const userBehaviorTrend = ref([]);

	const fetchOverview = () => {
		adminApi
			.getOverviewData()
			.then((res) => {
				if (res.code === 200) {
					overview.value = res.data;
				} else {
					message.error(res.message);
				}
			})
			.catch(() => {
				message.error('获取概览统计数据失败');
			});
	};

	const fetchTrend = () => {
		adminApi
			.getTrendData(
				trendType.value,
				trendStartDate.value.format('YYYY-MM-DD'),
				trendEndDate.value.format('YYYY-MM-DD'),
				trendGranularity.value
			)
			.then((res) => {
				if (res.code === 200) {
					trendData.value = res.data.trendData;
					nextTick(() => {
						updateTrendChart();
					});
				} else {
					message.error(res.message);
				}
			})
			.catch(() => {
				message.error('获取趋势统计数据失败');
			});
	};

	const fetchUserBehavior = () => {
		adminApi
			.getUserBehaviorData(
				behaviorType.value,
				trendStartDate.value.format('YYYY-MM-DD'),
				trendEndDate.value.format('YYYY-MM-DD'),
				trendGranularity.value
			)
			.then((res) => {
				if (res.code === 200) {
					// 保存接口返回的用户行为趋势数据
					userBehaviorTrend.value = res.data.trendData;
					nextTick(() => {
						updateUserBehaviorChart();
					});
				} else {
					message.error(res.message);
				}
			})
			.catch(() => {
				message.error('获取用户行为统计数据失败');
			});
	};

	const fetchLandlordPerformance = () => {
		adminApi
			.getLandlordPerformance()
			.then((res) => {
				if (res.code === 200) {
					landlordPerformance.value = res.data;
				} else {
					message.error(res.message);
				}
			})
			.catch(() => {
				message.error('获取房东运营数据失败');
			});
	};

	const fetchGeoDistribution = () => {
		adminApi
			.getHouseByLocation(geoType.value)
			.then((res) => {
				if (res.code === 200) {
					geoData.value = res.data;
					nextTick(() => {
						updateGeoChart();
					});
				} else {
					message.error(res.message);
				}
			})
			.catch(() => {
				message.error('获取地理分布数据失败');
			});
	};

	// 点击趋势查询按钮（同时更新趋势和用户行为图）
	const onFetchTrend = () => {
		fetchTrend();
		fetchUserBehavior();
	};

	// ----------------------
	// 生命周期钩子
	// ----------------------
	onMounted(() => {
		// trendChartInstance = echarts.init(trendChartContainer.value);
		geoChartInstance = echarts.init(geoChartContainer.value);
		userBehaviorChartInstance = echarts.init(userBehaviorChartContainer.value);

		fetchOverview();
		fetchTrend();
		fetchUserBehavior();
		fetchLandlordPerformance();
		fetchGeoDistribution();

		window.addEventListener('resize', () => {
			if (trendChartInstance) trendChartInstance.resize();
			if (geoChartInstance) geoChartInstance.resize();
			if (userBehaviorChartInstance) userBehaviorChartInstance.resize();
		});
	});

	onBeforeUnmount(() => {
		if (trendChartInstance) trendChartInstance.dispose();
		if (geoChartInstance) geoChartInstance.dispose();
		if (userBehaviorChartInstance) userBehaviorChartInstance.dispose();
	});
</script>

<style scoped>
	.container {
		overflow: hidden;
		padding: 16px;
	}
</style>
